package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import com.sky.utils.GetMethodAnnotation;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

//切面类
@Component
@Slf4j
@Aspect
public class AutoFillAspect {
    @Autowired
    private GetMethodAnnotation getMethodAnnotation;

    /**
     * 切入点
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut() {
    }

    //定义通知类型
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws Exception {
        log.info("开始公共字段自动注入");
        AutoFill autoFill = getMethodAnnotation.getMethod(joinPoint, AutoFill.class);
        OperationType value = autoFill.value();
        Object[] args = joinPoint.getArgs();//获取实体对象
        if (args == null || args.length == 0) {
            log.info("自动填充失败,实体对象为空");
            return;
        }
        Object entity = args[0];
        LocalDateTime now = LocalDateTime.now();
        Long people = BaseContext.getCurrentId();
        BaseContext.removeCurrentId();
        //利用JAVA反射进行映射赋值
        if (value == OperationType.INSERT) {
            //四个字段赋值
            Method SetCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);//匹配指定名称和参数的类的方法,此方法返回的Method对象
            Method SetCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            Method SetUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method SetUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            SetCreateTime.invoke(entity, now);
            SetUpdateTime.invoke(entity, now);
            SetUpdateUser.invoke(entity, people);
            SetCreateUser.invoke(entity, people);
            log.info("公共字段自动注入成功");

        } else if (value == OperationType.UPDATE) {
            //两个字段赋值
            Method SetUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method SetUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            SetUpdateTime.invoke(entity, now);
            SetUpdateUser.invoke(entity, people);
            log.info("公共字段自动注入成功");
        }
    }
}
